昨天有一小段未完成
在使用open()時,
如果要以POST的方式傳送資料,
必須修改MIME型態。
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
不然server不會理我。
接著要檢查XMLHttpRequest的狀態,
可以用readyState的值來檢查,httpRequest.readyState的值有五種:0:Request not initialized1:Server connection established2:Request received3:Processing request4:Request finished and response is ready
如果httpRequest.readyState的值為4時,
代表server已回傳所有的資訊了!
除了檢查request的狀態之外,
也可以透過status檢查server傳回的 HTTP 的狀態,httpRequest.status的值非常多種,如果成功的話會是200
另外常常看到的 404 not found代表了request失敗。
所以當readyState和status都是成功的狀態時,
就可以來做些甚麼事了:
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// do somethings;
}else{
// do somethings;
}
}
明天會用之前參加六角學院精神時光屋的活動提供的API實際來練習看看。